package utils

import (
	"fmt"
	"log"
)

// ParameterValidator 验证参数映射的正确性
type ParameterValidator struct {
	expectedSchema map[string]interface{}
	actualParams   map[string]interface{}
}

// NewParameterValidator 创建新的参数验证器
func NewParameterValidator(schema map[string]interface{}) *ParameterValidator {
	return &ParameterValidator{
		expectedSchema: schema,
	}
}

// ValidateParameters 验证参数是否符合OpenAPI规范
func (pv *ParameterValidator) ValidateParameters(params map[string]interface{}) error {
	pv.actualParams = params

	// 检查必需字段
	if required, ok := pv.expectedSchema["required"].([]interface{}); ok {
		for _, reqField := range required {
			fieldName := reqField.(string)
			if _, exists := params[fieldName]; !exists {
				return fmt.Errorf("required field missing: %s, available fields: %v", 
					fieldName, pv.getAvailableFieldNames(params))
			}
		}
	}

	// 检查字段名匹配
	if properties, ok := pv.expectedSchema["properties"].(map[string]interface{}); ok {
		for paramName := range params {
			if _, exists := properties[paramName]; !exists {
				log.Printf("[PARAMETER_VALIDATOR] Unexpected parameter: %s", paramName)
				return fmt.Errorf("unexpected parameter: %s, expected one of: %v", 
					paramName, pv.getExpectedFieldNames(properties))
			}
		}
	}

	return nil
}

// getExpectedFieldNames 获取期望的字段名列表
func (pv *ParameterValidator) getExpectedFieldNames(properties map[string]interface{}) []string {
	var names []string
	for name := range properties {
		names = append(names, name)
	}
	return names
}

// getAvailableFieldNames 获取实际可用的字段名列表
func (pv *ParameterValidator) getAvailableFieldNames(params map[string]interface{}) []string {
	var names []string
	for name := range params {
		names = append(names, name)
	}
	return names
}

// SuggestFieldMapping 建议字段映射修正
func (pv *ParameterValidator) SuggestFieldMapping(params map[string]interface{}) map[string]string {
	suggestions := make(map[string]string)
	
	if properties, ok := pv.expectedSchema["properties"].(map[string]interface{}); ok {
		// 常见的字段名映射建议
		mappings := map[string][]string{
			"name":     {"username", "user", "login", "account"},
			"username": {"name", "user", "login", "account"},
			"email":    {"mail", "e_mail", "emailAddress"},
			"password": {"pass", "pwd", "passwd"},
		}
		
		for expectedField := range properties {
			if _, exists := params[expectedField]; !exists {
				// 查找可能的映射
				if alternatives, ok := mappings[expectedField]; ok {
					for _, alt := range alternatives {
						if _, exists := params[alt]; exists {
							suggestions[alt] = expectedField
							log.Printf("[PARAMETER_VALIDATOR] Suggestion: rename '%s' to '%s'", alt, expectedField)
						}
					}
				}
			}
		}
	}
	
	return suggestions
}